package io.renren.modules.project.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import io.renren.common.utils.*;
import io.renren.common.utils.poi.ExcelStyleHelper;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.UserService;
import io.renren.modules.project.dao.ProjectContractDao;
import io.renren.modules.project.entity.ProjectContractEntity;
import io.renren.modules.project.entity.ProjectEntity;
import io.renren.modules.project.service.ProjectContractService;
import io.renren.modules.project.service.ProjectService;
import io.renren.modules.project.vo.ContractVoEntity;
import io.renren.modules.project.vo.ProjectVoEntity;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserRoleEntity;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.vo.UserVoEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.transaction.annotation.Transactional;


@Service("projectContractService")
public class ProjectContractServiceImpl extends ServiceImpl<ProjectContractDao, ProjectContractEntity> implements ProjectContractService {

    @Autowired
    public ProjectService projectService;

    @Autowired
    public SysUserRoleService sysUserRoleService;

    @Autowired
    public SysUserService sysUserService;

    @Autowired
    public SysUserDao sysUserDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String)params.get("key");
        String startDate = (String)params.get("startDate");
        String endDate = (String)params.get("endDate");
        boolean isAsc = params.get("order").equals("asc");
        Page<ProjectContractEntity> page = this.selectPage(
                new Query<ProjectContractEntity>(params).getPage(),
                new EntityWrapper<ProjectContractEntity>()
                .and(StringUtils.isNotBlank(startDate) , "date_format(contract_create_time,'%Y-%m-%d')>={0}",startDate)
                .and(StringUtils.isNotBlank(endDate) , "date_format(contract_create_time,'%Y-%m-%d')<={0}",endDate)
                .andNew(StringUtils.isNotBlank(key), "contract_name like {0} or contract_no like {0} or contract_authorize like {0} or contract_origin like {0}" ,
                        "%" + key.trim() + "%")
                .orderBy("id",isAsc )
        );
        //查找合同对应的项目
        for ( ProjectContractEntity entity: page.getRecords() ) {
            Map<String, Object> parms = new HashMap<>();
            parms.put("contractNo", entity.getContractNo());
            parms.put("pStage", "1");
            entity.setProjectList( projectService.queryList(parms) );
        }
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ContractVoEntity> querySignList(Map<String, Object> params){
        List<ContractVoEntity> list = this.baseMapper.getSignList(params);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ProjectContractEntity> queryList(Map<String, Object> params) {
        String key = (String)params.get("key");
        String startDate = (String)params.get("startDate");
        String endDate = (String)params.get("endDate");
        String order = (String)params.get("order");
        String sidx = (String)params.get("sidx");
        //业务负责人
        String contractBusiness = (String)params.get("business");

        List<ProjectContractEntity> list = this.selectList(
                new EntityWrapper<ProjectContractEntity>().like(StringUtils.isNotBlank(key),"contract_name", key )
                        .and(StringUtils.isNotBlank(startDate), "date_format(contract_create_time,'%Y-%m-%d')>={0}", startDate)
                        .and(StringUtils.isNotBlank(endDate), "date_format(contract_create_time,'%Y-%m-%d')<={0}", endDate)
                        .eq(StringUtils.isNotBlank(contractBusiness), "contract_business", contractBusiness)
                        .orderBy( sidx,order.equals("asc"))
        );
        return  list;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> getBusinessList(){
        return this.baseMapper.getAllBusinessList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectContractEntity getByContractNo(String contractNo){
        return this.selectOne(new EntityWrapper<ProjectContractEntity>().eq("contract_no", contractNo));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ProjectContractEntity entity) {
        entity.setContractStage(1L);
        entity.setContractCreateTime( new Date());
        this.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProjectContractEntity entity) {
        this.updateAllColumnById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] roleIds) {
        //删除
        this.deleteBatchIds(Arrays.asList(roleIds));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getMaxContractNo(){
        //获取当前年月
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        String ymKey = String.valueOf(year) + String.format("%02d", month);
        //获取当前年月的合同编号列表
        List<ProjectContractEntity> list = this.selectList(
          new EntityWrapper<ProjectContractEntity>().like( StringUtils.isNotBlank(ymKey),"contract_no", ymKey)
        );
        int maxsize = list.size();
        // 查找最大的合同编号后两位数
        for (ProjectContractEntity contractEntity : list){
            int cursize = Integer.parseInt(contractEntity.getContractNo().replace(ymKey , ""));
            if(cursize > maxsize){
                maxsize = cursize;
            }
        }
        return ymKey + String.format("%02d", maxsize + 1);
    }

    /**
     * 导出项目excel
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Workbook exportProExcel(Map<String, Object> params){
        List<ProjectContractEntity> list = this.queryList(params);

        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        int rowIndex = 0;

        //生成一个表格，设置表格名称
        HSSFSheet sheet = workbook.createSheet("sheet1");
        // 字段字体设置
        HSSFFont tfont = workbook.createFont();
        tfont.setFontName("黑体");
        tfont.setFontHeightInPoints((short) 12);
        tfont.setBold(true);   //字体加粗
        // 字段表格样式
        HSSFCellStyle tstyle = workbook.createCellStyle();
        tstyle.setFont(tfont);
        tstyle.setVerticalAlignment(VerticalAlignment.CENTER);  // 垂直居中
        //设置表格列宽度
        sheet.setColumnWidth(0, 40 * 100);
        sheet.setColumnWidth(1, 170 * 100);
        sheet.setColumnWidth(2, 130 * 100);
        sheet.setColumnWidth(3, 40 * 100);
        sheet.setColumnWidth(4, 40 * 100);
        sheet.setColumnWidth(5, 40 * 100);
        sheet.setColumnWidth(6, 40 * 100);
        sheet.setColumnWidth(7, 100 * 100);
        sheet.setColumnWidth(8, 40 * 100);
        sheet.setColumnWidth(9, 40 * 100);

        String[] fields = new String[]{"合同编号","合同名称","委托单位","联系人","联系电话","合同类型","合同金额","业务来源","签订时间","创建时间"};
        // 字段行
        HSSFRow tRow = sheet.createRow(rowIndex++);
        tRow.setHeight((short) 420);
        HSSFCell tcell;
        int column = 0;
        for (String field: fields) {
            tcell = tRow.createCell(column++);
            tcell.setCellValue(new HSSFRichTextString(field));
            tcell.setCellStyle(tstyle);
        }

        for (ProjectContractEntity entity : list) {
            HSSFRow cRow = sheet.createRow(rowIndex++);
            cRow.setHeight((short) 280);
            HSSFCell cell;
            cell = cRow.createCell(0);
            cell.setCellValue(new HSSFRichTextString(entity.getContractNo()));
            cell = cRow.createCell(1);
            cell.setCellValue(new HSSFRichTextString(entity.getContractName()));
            cell = cRow.createCell(2);
            cell.setCellValue(new HSSFRichTextString(entity.getContractAuthorize()));
            cell = cRow.createCell(3);
            cell.setCellValue(new HSSFRichTextString(entity.getUserName()));
            cell = cRow.createCell(4);
            cell.setCellValue(new HSSFRichTextString(entity.getUserPhone()));
            cell = cRow.createCell(5);
            cell.setCellValue(new HSSFRichTextString(entity.getContractType() == 0L ? "合同委托":"一般合同"));
            cell = cRow.createCell(6);
            cell.setCellValue(new HSSFRichTextString(String.format("%.2f", entity.getContractMoney())));
            // 字段表格样式
            HSSFCellStyle fstyle = workbook.createCellStyle();
            fstyle.setAlignment(HorizontalAlignment.RIGHT);
            cell.setCellStyle(fstyle);

            cell = cRow.createCell(7);
            cell.setCellValue(new HSSFRichTextString(entity.getContractOrigin()));
            cell = cRow.createCell(8);
            cell.setCellValue(new HSSFRichTextString(entity.getContractAddTime() == null ? "" : DateUtils.format(entity.getContractAddTime())));
            cell = cRow.createCell(9);
            cell.setCellValue(new HSSFRichTextString(entity.getContractCreateTime() == null ? "" : DateUtils.format(entity.getContractCreateTime())));

        }
        return workbook;
    }

    /**
     * 导出签收项目的合同excel
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Workbook exportSignExcel(Map<String, Object> params){
        List<ContractVoEntity> list = this.querySignList(params);

        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        int rowIndex = 0;

        //生成一个表格，设置表格名称
        HSSFSheet sheet = workbook.createSheet("sheet1");

        //设置表格列宽度
        sheet.setColumnWidth(0, 40 * 100);
        sheet.setColumnWidth(1, 170 * 100);
        sheet.setColumnWidth(2, 40 * 100);
        sheet.setColumnWidth(3, 80 * 100);
        sheet.setColumnWidth(4, 40 * 100);
        sheet.setColumnWidth(5, 40 * 100);
        sheet.setColumnWidth(6, 130 * 100);
        sheet.setColumnWidth(7, 40 * 100);
        sheet.setColumnWidth(8, 40 * 100);


        String[] fields = new String[]{"合同编号","合同名称","业务负责人","业务来源","已签项目","合计项目","项目名称","是否签收"};
        // 字段行
        HSSFRow tRow = sheet.createRow(rowIndex++);
        tRow.setHeight((short) 420);
        HSSFCell tcell;
        int column = 0;
        for (String field: fields) {
            tcell = tRow.createCell(column++);
            tcell.setCellValue(new HSSFRichTextString(field));
            ExcelStyleHelper.setTileCell(workbook,tcell);
        }
        int tempIndex = rowIndex;
        int sigNum = 0;
        for(int index = 0; index < list.size(); index++) {
            HSSFRow cRow = sheet.createRow(rowIndex++);
            cRow.setHeight((short) 280);
            HSSFCellStyle cstyle = workbook.createCellStyle();
            cstyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cRow.setRowStyle(cstyle);
            HSSFCell cell;
            cell = cRow.createCell(0);
            cell.setCellValue(new HSSFRichTextString(list.get(index).getContractNo()));
            cell = cRow.createCell(1);
            cell.setCellValue(new HSSFRichTextString(list.get(index).getContractName()));
            cell = cRow.createCell(2);
            cell.setCellValue(new HSSFRichTextString(list.get(index).getContractBusiness()));
            cell = cRow.createCell(3);
            cell.setCellValue(new HSSFRichTextString(list.get(index).getContractOrigin()));
            cell = cRow.createCell(6);
            cell.setCellValue(new HSSFRichTextString(list.get(index).getProjectName()));
            cell = cRow.createCell(7);
            cell.setCellValue(new HSSFRichTextString(list.get(index).getIsSign() != null && list.get(index).getIsSign() == 1? "是": "否"));
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.RIGHT);
            cell.setCellStyle(style);
            if(list.get(index).getIsSign() != null && list.get(index).getIsSign() == 1) {
                ExcelStyleHelper.setCellRightTop(cell);
                ExcelStyleHelper.setFontColor(workbook,cell,Font.COLOR_RED);
                // 已经签收加1
                sigNum ++;
            }

            // 合并单元格
            if ( (index < list.size() - 1  && !list.get(index).getContractNo().equals(list.get(index + 1).getContractNo())) || index == list.size() - 1 ) {
                if (tempIndex != (rowIndex - 1)) {
                    //指定合并开始行、合并结束行 合并开始列、合并结束列
                    //添加要合并地址到表格
                    for (int i = 0; i < 6; i++)
                    sheet.addMergedRegion(new CellRangeAddress(tempIndex, rowIndex -1, i, i));
                }

                style = workbook.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);
                // 合计项目数
                cell = sheet.getRow(tempIndex).createCell(4);
                cell.setCellValue( sigNum );
                cell.setCellStyle(style);
                cell = sheet.getRow(tempIndex ).createCell(5);
                cell.setCellValue( rowIndex - tempIndex );
                cell.setCellStyle(style);

                // 签收置0，重新算
                sigNum = 0;
                tempIndex = rowIndex;
            }

        }

        return workbook;
    }
}